package com.student.enrollment.repository;

import com.student.common.entity.Enrollment;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

/**
 * 选课数据访问接口
 * 
 * @author student
 * @date 2025
 */
@Repository
public interface EnrollmentRepository extends JpaRepository<Enrollment, Long> {
    
    /**
     * 检查学生是否已选择某课程
     */
    boolean existsByStudentIdAndCourseIdAndSemester(String studentId, String courseId, String semester);
    
    /**
     * 根据学生ID、课程ID和学期查找选课记录
     */
    Enrollment findByStudentIdAndCourseIdAndSemester(String studentId, String courseId, String semester);
    
    /**
     * 根据学生ID查询选课记录
     */
    Page<Enrollment> findByStudentId(String studentId, Pageable pageable);
    
    /**
     * 根据学生ID和学期查询选课记录
     */
    Page<Enrollment> findByStudentIdAndSemester(String studentId, String semester, Pageable pageable);
    
    /**
     * 根据课程ID查询选课记录
     */
    Page<Enrollment> findByCourseId(String courseId, Pageable pageable);
    
    /**
     * 根据课程ID和学期查询选课记录
     */
    Page<Enrollment> findByCourseIdAndSemester(String courseId, String semester, Pageable pageable);
    
    /**
     * 统计指定学期的选课数量
     */
    long countBySemester(String semester);
    
    /**
     * 根据条件查询选课记录
     */
    @Query("SELECT e FROM Enrollment e WHERE " +
           "(:studentId IS NULL OR e.studentId LIKE %:studentId%) AND " +
           "(:courseId IS NULL OR e.courseId LIKE %:courseId%) AND " +
           "(:semester IS NULL OR e.semester = :semester) AND " +
           "(:status IS NULL OR e.status = :status)")
    Page<Enrollment> findByConditions(@Param("studentId") String studentId, 
                                     @Param("courseId") String courseId, 
                                     @Param("semester") String semester,
                                     @Param("status") String status,
                                     Pageable pageable);
}
